package com.cloudpivot.receivales.meetingtemp.service;

import cn.hutool.core.img.ImgUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.cloudpivot.receivales.meetingtemp.entity.MeetingTempEntity;
import com.cloudpivot.receivales.meetingtemp.entity.MeetingTempItemEntity;
import com.cloudpivot.receivales.meetingtemp.entity.MeetingTempPicItemEntity;
import com.cloudpivot.receivales.meetingtemp.repository.MeetingTempListRepository;
import com.cloudpivot.receivales.meetingtemp.repository.MeetingTempAttListRepository;
import com.cloudpivot.receivales.meetingtemp.repository.MeetingTempRepository;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * 会议临时处理 服务类
 */
@Service
@Slf4j
public class MeetingTempServiceImpl {

    @Value("${meeting.modepath}")
    private String MODEPATH;

    @Value("${meeting.outdic}")
    private String OUTPATH;
    @Value("${myprops.cpurl}")
    private String CPURL;

    @Autowired
    private MeetingTempRepository meetingTempRepository;

    @Autowired
    private MeetingTempListRepository meetingTempListRepository;

    @Autowired
    private MeetingTempAttListRepository meetingTempAttListRepository;

    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;

    public void getMeettingModelEntity(String meettingName){
        //获取会议主队项
        MeetingTempEntity entity = meetingTempRepository.getMeetingEntity(meettingName);
        //获取会议明细
        List<MeetingTempItemEntity> items = meetingTempListRepository.getMeetingItems(entity.getId());
        //获取会议图像list
        List<MeetingTempPicItemEntity> picItems = meetingTempAttListRepository.getMeetingPicItems(entity.getId());
        //获取会议附件(会议通知)
        List<MeetingTempPicItemEntity> attItems = meetingTempAttListRepository.getMeetingAttItems(entity.getId());
        //创建poi对象
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(entity));
        //放入poi对象子表
        TableRenderData _itemTable=buildTable(items);
        jsonObject.put("meeting_table", _itemTable );
        //测试用
//        String _refId="DIRE_a382b231dce44c68af4afd82e10f4016签到表1.jpg";
        //循环放入 pic
        if (!Objects.isNull(picItems)) {
            int i=1;
            for (MeetingTempPicItemEntity picEntity : picItems) {
                if(i==5){
                    break;
                }
                jsonObject.put("pic" + i, setPicture(picEntity.getRefId()));
                i++;
            }
        }

        //对象无误 开始生成结构
        createMeetingDoc(jsonObject, attItems);
        log.info("生成完毕");
    }

    /**
     * 核心  整理文件
     * @param entity
     * @param attItems
     */
    private void createMeetingDoc(JSONObject entity,List<MeetingTempPicItemEntity> attItems) {
        try {
            XWPFTemplate template = XWPFTemplate.compile(MODEPATH + "/meetingModel.docx");
            template.render(entity);
            //创建一个已entity.getName()的文件夹
            String dicName=OUTPATH+"/"+entity.getString("meetingname");
            new File(dicName).mkdirs();
            template.writeAndClose(new FileOutputStream(dicName + "/会议报告-主(含会议图片).docx"));

            //循环取附件
            if(!Objects.isNull(attItems)){
                for (MeetingTempPicItemEntity attEntity : attItems) {
                    String _base64 = attEntity.getRefId();
                    convertBase64ToFile(getSignBase64(_base64), dicName + "/会议图." + attEntity.getFileExtension());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //整理子表
    private TableRenderData buildTable(List<MeetingTempItemEntity> items) {
        try {
            if(Objects.isNull(items)||items.isEmpty()){
                return null;
            }
            //做表头
            RowRenderData rowTitle = Rows.of("费用预算项目", "数量", "预算小计", "决算金额").center().textBold().create();

            if (Objects.isNull(items)) {
                RowRenderData[] args = new RowRenderData[1];
                args[0] = rowTitle;
                //只返回表头||返回空
                TableRenderData table = Tables.of(args).create();
                return table;
            } else {
                //返回表
                RowRenderData[] args = new RowRenderData[items.size() + 1];
                args[0] = rowTitle;
                for (int i = 0; i < items.size(); i++) {
                    MeetingTempItemEntity item = items.get(i);
                    //args[i + 1] = Rows.of(item.getNew_name(), item.getNew_productname(), item.getNew_add_code(), item.getNew_number(), item.getNew_price(), item.getNew_total()).center().create();
                    //列的上下一定要对上
                    args[i + 1] = Rows.of(objectToStr(item.getExpensebudgetitem()), objectToStr(item.getAmount()), objectToStr(item.getBudgetsubtotal()), objectToStr(item.getFinalsettlementamount())).center().create();
                }
                TableRenderData table = Tables.of(args).create();
                return table;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建pic到docx
     * @param refId
     * @return
     */
    private PictureRenderData setPicture(String refId) {
        try {
            PictureRenderData pictures = Pictures.ofBase64(getSignBase64(refId), PictureType.PNG).size(768, 480).altMeta("无签名").create();
            return pictures;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 创建附件到指定目录
     */
    private File convertBase64ToFile(String base64String, String outputFilePath) {
        try {
            // 解码 Base64 字符串为 byte[]
            byte[] decodedBytes = Base64.getDecoder().decode(base64String);
            // 创建目标文件
            File outputFile = new File(outputFilePath);
            // 确保父目录存在
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            // 写入文件流
            try (OutputStream outputStream = new FileOutputStream(outputFile)) {
                outputStream.write(decodedBytes);
            }
            return outputFile;
        } catch (IOException e) {
//            throw new RuntimeException("Base64 转文件失败: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 通过url获取图片
     * demo DIRE_a382b231dce44c68af4afd82e10f4016签到表1.jpg
     * @param refId
     * @return
     */
    private String getSignBase64(String refId) {
        try {
            String url = String.format("%s%s%s", CPURL, "api/aliyun/download?refId=", URLEncoder.encode(refId, "utf-8"));
            System.out.println("url===>>>" + url);
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] ret = httpAPIServiceForDing.doGetToBytes(url);
            String base64 = encoder.encodeToString(ret);
//            BufferedImage inImage = ImgUtil.toImage(base64);
//            Image outImage=ImgUtil.rotate(inImage, 0);
//            String outBase64 = ImgUtil.toBase64(outImage, "png");
//            System.out.println(outBase64.length());
            return base64;
        } catch (Exception e) {
//            e.printStackTrace();
            return null;
        }
    }

    private String objectToStr(Object object) {
        try {
            if (Objects.isNull(object)) {
                return "-";
            }else{
                return object.toString();
            }
        } catch (Exception e) {
            return "-";
        }
    }
}
